package cn.iocoder.yudao.module.ai.graph.config;

import cn.iocoder.yudao.module.ai.graph.dispatcher.CustomerServiceDispatcher;
import cn.iocoder.yudao.module.ai.graph.node.customerservice.*;
import com.alibaba.cloud.ai.graph.GraphRepresentation;
import com.alibaba.cloud.ai.graph.KeyStrategyFactory;
import com.alibaba.cloud.ai.graph.KeyStrategyFactoryBuilder;
import com.alibaba.cloud.ai.graph.StateGraph;
import com.alibaba.cloud.ai.graph.action.AsyncEdgeAction;
import com.alibaba.cloud.ai.graph.exception.GraphStateException;
import com.alibaba.cloud.ai.graph.state.strategy.ReplaceStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static com.alibaba.cloud.ai.graph.action.AsyncNodeAction.node_async;

/**
 * 客服工作流配置 - 展示完整的人工打断和恢复功能
 * 
 * 工作流说明：
 * 1. 客户问题分类（自动）
 * 2. 初步回复生成（自动）
 * 3. 人工审核点（打断） - 客服人员可以修改回复或选择处理方式
 * 4. 根据审核结果分发：
 *    - 直接发送回复
 *    - 转人工客服
 *    - 升级到高级支持
 * 5. 发送回复（自动）
 * 6. 满意度调查（可选打断）
 * 
 * @author yudao
 * @since 2025/10/17
 */
@Configuration
public class CustomerServiceGraphConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(CustomerServiceGraphConfiguration.class);

    @Bean
    public StateGraph customerServiceGraph(ChatClient.Builder chatClientBuilder) throws GraphStateException {
        // 定义状态管理策略
        KeyStrategyFactory keyStrategyFactory = new KeyStrategyFactoryBuilder()
                // 客户信息
                .addPatternStrategy("customer_id", new ReplaceStrategy())
                .addPatternStrategy("customer_query", new ReplaceStrategy())
                .addPatternStrategy("customer_context", new ReplaceStrategy())
                
                // 分类结果
                .addPatternStrategy("query_category", new ReplaceStrategy())
                .addPatternStrategy("query_priority", new ReplaceStrategy())
                .addPatternStrategy("query_sentiment", new ReplaceStrategy())
                
                // AI 生成的回复
                .addPatternStrategy("ai_reply", new ReplaceStrategy())
                .addPatternStrategy("ai_confidence", new ReplaceStrategy())
                
                // 人工审核结果
                .addPatternStrategy("human_approved", new ReplaceStrategy())
                .addPatternStrategy("human_modified_reply", new ReplaceStrategy())
                .addPatternStrategy("human_decision", new ReplaceStrategy())
                .addPatternStrategy("human_comments", new ReplaceStrategy())
                
                // 最终回复
                .addPatternStrategy("final_reply", new ReplaceStrategy())
                .addPatternStrategy("send_status", new ReplaceStrategy())
                
                // 满意度调查
                .addPatternStrategy("satisfaction_score", new ReplaceStrategy())
                .addPatternStrategy("satisfaction_feedback", new ReplaceStrategy())
                
                // 流程控制
                .addPatternStrategy("next_node", new ReplaceStrategy())
                .addPatternStrategy("thread_id", new ReplaceStrategy())
                .build();

        // 构建工作流图
        StateGraph stateGraph = new StateGraph(keyStrategyFactory)
                // 添加节点
                .addNode("classify", node_async(new ClassifyQueryNode(chatClientBuilder)))
                .addNode("generate_reply", node_async(new GenerateReplyNode(chatClientBuilder)))
                .addNode("human_review", node_async(new HumanReviewNode()))
                .addNode("send_reply", node_async(new SendReplyNode()))
                .addNode("transfer_to_human", node_async(new TransferToHumanNode()))
                .addNode("escalate", node_async(new EscalateNode()))
                .addNode("satisfaction_survey", node_async(new SatisfactionSurveyNode()))
                
                // 定义边（流程）
                .addEdge(StateGraph.START, "classify")
                .addEdge("classify", "generate_reply")
                .addEdge("generate_reply", "human_review")
                
                // 人工审核后的条件分发
                .addConditionalEdges("human_review", 
                    AsyncEdgeAction.edge_async(new CustomerServiceDispatcher()), 
                    Map.of(
                        "send_reply", "send_reply",
                        "transfer_to_human", "transfer_to_human",
                        "escalate", "escalate",
                        StateGraph.END, StateGraph.END
                    ))
                
                .addEdge("send_reply", "satisfaction_survey")
                .addEdge("transfer_to_human", StateGraph.END)
                .addEdge("escalate", StateGraph.END)
                .addEdge("satisfaction_survey", StateGraph.END);

        // 生成并打印工作流图（PlantUML 格式）
        GraphRepresentation representation = stateGraph.getGraph(
            GraphRepresentation.Type.PLANTUML,
            "Customer Service Workflow with Human Interruption"
        );
        
        logger.info("\n" + "=".repeat(80));
        logger.info("Customer Service Workflow - PlantUML");
        logger.info("=".repeat(80));
        logger.info("\n{}\n", representation.content());
        logger.info("=".repeat(80));
        logger.info("工作流节点说明：");
        logger.info("  1. classify        - AI 自动分类客户问题");
        logger.info("  2. generate_reply  - AI 生成初步回复");
        logger.info("  3. human_review    - 【人工打断点】客服审核回复");
        logger.info("  4. send_reply      - 发送回复给客户");
        logger.info("  5. transfer_to_human - 转人工客服");
        logger.info("  6. escalate        - 升级到高级支持");
        logger.info("  7. satisfaction_survey - 【可选打断点】满意度调查");
        logger.info("=".repeat(80) + "\n");

        return stateGraph;
    }
}

